package com.xms.schema.api.controller;

import com.xms.core.exception.XmsException;
import com.xms.core.model.KeyValuePair;
import com.xms.schema.api.model.CreateAttributeModel;
import com.xms.schema.core.AttributeTypeIds;
import com.xms.schema.entity.*;
import com.xms.schema.service.attribute.IAttributeCreaterService;
import com.xms.schema.service.attribute.IAttributeFinderService;
import com.xms.schema.service.entity.IEntityFinderService;
import com.xms.utils.CollectionUtil;
import com.xms.utils.StringUtil;
import com.xms.utils.UUIDUtil;
import com.xms.web.framework.controller.ApiBaseController;
import com.xms.web.framework.model.JsonResultObject;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * AttributeCreaterController
 * </p>
 *
 * @author migo
 * @since 2021/9/16
 */
@RestController
@RequestMapping("{org}/api/schema/attribute")
public class AttributeCreaterController extends ApiBaseController {
    private IEntityFinderService _entityFinderService;
    private IAttributeCreaterService _attributeCreaterService;
    private IAttributeFinderService _attributeFinderService;
    @Autowired
    public void AttributeCreaterController(IEntityFinderService entityFinderService,
                                           IAttributeCreaterService attributeCreaterService,
                                           IAttributeFinderService attributeFinderService) {
        _entityFinderService = entityFinderService;
        _attributeCreaterService = attributeCreaterService;
        _attributeFinderService = attributeFinderService;
    }

    @ApiOperation("新建字段")
    @PostMapping("create")
    public JsonResultObject create(@RequestBody CreateAttributeModel model) throws XmsException, SQLException {
        Entity entity = _entityFinderService.getById(model.EntityId);
        if (entity == null) {
            return JNotFound();
        }
        Attribute attr = _attributeFinderService.getByName(model.EntityId, model.Name);
        if (attr != null) {
            return JError("字段名称已存在");
        }
        Attribute attrInfo = new Attribute();
        attrInfo.setEntityid(entity.getEntityid());
        attrInfo.setEntityname(entity.getName());
        attrInfo.setName(model.Name.trim().toLowerCase());
        attrInfo.setLocalizedname(model.LocalizedName);
        attrInfo.setAttributeid(UUIDUtil.get());
        attrInfo.setIsnullable(true);
        attrInfo.setIsrequired(model.IsRequired);
        attrInfo.setLogenabled(model.LogEnabled);
        attrInfo.setIscustomizable(true);
        attrInfo.setIscustomfield(true);
        attrInfo.setIsprimaryfield(false);
        attrInfo.setAuthorizationenabled(model.AuthorizationEnabled);
        attrInfo.setCreatedby(_currentUser.getUser().SystemUserId);
        attrInfo.setDescription(model.Description);
        attrInfo.setValuetype(model.ValueType);
        attrInfo.setCreatedon(LocalDateTime.now());
        switch (model.AttributeTypeName) {
            case AttributeTypeIds.NVARCHAR:
                attrInfo.setMaxlength(model.MaxLength);
                attrInfo.setDataformat(model.TextFormat);
                attrInfo.setDefaultvalue(model.DefaultValue);
                if (model.ValueType == 2) {
                    attrInfo.setFormulaexpression(model.FormulaExpression);
                }
                break;

            case AttributeTypeIds.NTEXT:
                attrInfo.setDataformat(model.NTextFormat);
                break;

            case AttributeTypeIds.INT:
                model.IntMinValue = model.IntMinValue <= -2147483647 ? -2147483646 : model.IntMinValue;
                model.IntMaxValue = model.IntMaxValue >= 2147483647 ? 2147483646 : model.IntMaxValue;
                attrInfo.setMinvalue((double) model.IntMinValue);
                attrInfo.setMaxvalue((double) model.IntMaxValue);
                attrInfo.setDefaultvalue(model.DefaultValue);
                if (model.ValueType == 2) {
                    attrInfo.setFormulaexpression(model.FormulaExpression);
                } else if (model.ValueType == 3) {
                    attrInfo.setSummaryentityid(model.SummaryEntityId);
                    attrInfo.setSummaryexpression(model.SummaryExpression);
                }
                break;

            case AttributeTypeIds.FLOAT:
                model.FloatMinValue = model.FloatMinValue <= -2147483647f ? -2147483646f : model.FloatMinValue;
                model.FloatMaxValue = model.FloatMaxValue >= 2147483647f ? 2147483640f : model.FloatMaxValue;
                attrInfo.setPrecision(model.FloatPrecision);
                attrInfo.setMinvalue((double) model.FloatMinValue);
                attrInfo.setMaxvalue((double) model.FloatMaxValue);
                attrInfo.setDefaultvalue(model.DefaultValue);
                if (model.ValueType == 2) {
                    attrInfo.setFormulaexpression(model.FormulaExpression);
                } else if (model.ValueType == 3) {
                    attrInfo.setSummaryentityid(model.SummaryEntityId);
                    attrInfo.setSummaryexpression(model.SummaryExpression);
                }
                break;

            case AttributeTypeIds.MONEY:
                model.MoneyMinValue = model.MoneyMinValue <= -2147483647 ? -2147483646 : model.MoneyMinValue;
                model.MoneyMaxValue = model.MoneyMaxValue >= 2147483647 ? 2147483646 : model.MoneyMaxValue;
                attrInfo.setPrecision(model.MoneyPrecision);
                attrInfo.setMinvalue((double) model.MoneyMinValue);
                attrInfo.setMaxvalue((double) model.MoneyMaxValue);
                attrInfo.setDefaultvalue(model.DefaultValue);
                if (model.ValueType == 2) {
                    attrInfo.setFormulaexpression(model.FormulaExpression);
                } else if (model.ValueType == 3) {
                    attrInfo.setSummaryentityid(model.SummaryEntityId);
                    attrInfo.setSummaryexpression(model.SummaryExpression);
                }
                break;

            case AttributeTypeIds.PICKLIST:
                attrInfo.setDisplaystyle(model.OptionSetType);
                if (CollectionUtil.notEmpty(model.IsCommonOptionSet) && model.IsCommonOptionSet[0]) {
                    attrInfo.setOptionsetid(model.CommonOptionSet);
                } else {
                    if (CollectionUtil.isEmpty(model.OptionSetName)) {
                        return JError("字段选项不能为空");
                    }
                    //新建选项集
                    OptionSet os = new OptionSet();
                    os.setOptionsetid(UUIDUtil.get());
                    os.setName(model.Name);
                    os.setIspublic(false);
                    os.setCreatedby(attrInfo.getCreatedby());
                    os.setCreatedon(attrInfo.getCreatedon());
                    os.setOrganizationid(_currentUser.getUser().OrganizationId);
                    List<OptionSetDetail> details = new ArrayList<>();
                    int i = 0;
                    for (String item : model.OptionSetName) {
                        if (StringUtil.isEmpty(item)) {
                            continue;
                        }
                        OptionSetDetail osd = new OptionSetDetail();
                        osd.setOptionsetdetailid(UUIDUtil.get());
                        osd.setOptionsetid(os.getOptionsetid());
                        osd.setName(item);
                        osd.setValue(model.OptionSetValue[i]);
                        osd.setIsselected(model.IsSelectedOption[i]);
                        osd.setDisplayorder(i);
                        details.add(osd);
                        i++;
                    }
                    attrInfo.setOptionsetid(os.getOptionsetid());
                    os.setItems(details);
                    attrInfo.setOptionset(os);
                }
                break;

            case AttributeTypeIds.BIT:
                if (CollectionUtil.isEmpty(model.BitOptionName)) {
                    return JError("字段选项不能为空");
                }
                //新建选项集
                List<StringMap> pickListItems = new ArrayList<>();
                int j = 0;
                for (String item : model.BitOptionName) {
                    StringMap s = new StringMap();
                    s.setStringmapid(UUIDUtil.get());
                    s.setName(item);
                    s.setValue(j == 0 ? 1 : 0);//第一项为true选项
                    s.setDisplayorder(j);
                    s.setAttributeid(attrInfo.getAttributeid());
                    s.setEntityname(attrInfo.getEntityname());
                    s.setAttributename(attrInfo.getName());
                    j++;
                    pickListItems.add(s);
                }
                attrInfo.setPicklists(pickListItems);
                break;

            case AttributeTypeIds.DATETIME:
                attrInfo.setDataformat(model.DateTimeFormat);
                break;

            case AttributeTypeIds.LOOKUP:
                attrInfo.setReferencedentityid(model.LookupEntity);
                Entity referencedEntity = _entityFinderService.getById(model.LookupEntity);
                attrInfo.setReferencedentityname(referencedEntity.getName());
                attrInfo.setDisplaystyle(model.LookupType);
                break;

            case AttributeTypeIds.PARTYLIST:
                attrInfo.setDataformat(model.PartyListFormat);
                break;
        }
        attrInfo.setAttributetypename(model.AttributeTypeName);
        _attributeCreaterService.create(attrInfo);
        return JCreateSuccess(KeyValuePair.build("id", attrInfo.getAttributeid()));
    }
}
